import useSettingsStore from './settings';
import useRouteStore from './route';
import useMenuStore from './menu';
import router from '@/router';
import apiUser from '@/api/modules/user';
import API from '@/api/api';

function getStore(name: string) {
  try {
    return JSON.parse(localStorage[name]);
  } catch (e) {
    return {};
  }
}
const useUserStore = defineStore(
  // 唯一ID
  'user',
  () => {
    const routeStore = useRouteStore();
    const menuStore = useMenuStore();
    const userInfo = ref<any>(getStore('userInfo'));
    const platType = ref(localStorage.getItem('platType'));
    const account = computed(() => {
      return userInfo.value?.userName || '';
    });
    const token = ref(localStorage.token ?? '');
    const avatar = ref(localStorage.avatar ?? '');
    const permissions = ref<string[]>([]);
    const isLogin = computed(() => {
      if (token.value) {
        return true;
      }
      return false;
    });
    window.addEventListener('storage', function (event) {
      // 如果token在其他页面被修改  刷新页面
      if (event.key == 'token') {
        location.reload();
      }
    });

    // 登录
    async function login(data: {
      account: string;
      password: string;
      platType: string;
    }) {
      menuStore.setActived(data.platType == '2' ? 0 : 1);
      const res = await API.sysLoginController.login({
        account: data.account,
        smsCode: data.password,
        platType: data.platType,
      });

      localStorage.setItem('token', res.token);
      localStorage.setItem('platType', data.platType);
      token.value = res.token;
      platType.value = data.platType;
      const userInfoResponse = await API.sysLoginController.getInfo();
      userInfo.value = userInfoResponse;
      localStorage.setItem('userInfo', JSON.stringify(userInfoResponse));
    }
    // 登出
    async function logout(redirect = router.currentRoute.value.fullPath) {
      localStorage.setItem('token', ' ');
      localStorage.clear();
      token.value = '';
      userInfo.value = {};
      permissions.value = [];

      routeStore.removeRoutes();
      router.push({
        name: platType.value == '2' ? 'login2' : 'login',
        // query: {
        //   ...(router.currentRoute.value.path !==
        //     settingsStore.settings.home.fullPath &&
        //     router.currentRoute.value.name !== 'login' && { redirect }),
        // },
      });
      platType.value = null;
    }
    // 获取权限
    async function getPermissions() {
      const res = await apiUser.permission();
      permissions.value = res.data.permissions;
    }
    // 修改密码
    async function editPassword(data: {
      password: string;
      newpassword: string;
    }) {
      await apiUser.passwordEdit(data);
    }

    return {
      account,
      token,
      avatar,
      permissions,
      isLogin,
      login,
      logout,
      getPermissions,
      editPassword,
      userInfo,
      platType,
    };
  }
);

export default useUserStore;
